const WXAPI = require('apifm-wxapi')
const TOOLS = require('../../utils/tools.js')
const AUTH = require('../../utils/auth.js')
const CONFIG = require('../../config.js')
const APP = getApp()
const generateId = () => Date.now().toString(36) + Math.random().toString(36).substr(2, 5);


Page({
  data: {
    qj: wx.getStorageSync("qj") ? wx.getStorageSync("qj") : 'bz',
    zdydh: wx.getStorageSync("zdydh") ? wx.getStorageSync("zdydh") : '',
    zdylogo: wx.getStorageSync("zdylogo") ? wx.getStorageSync("zdylogo") : '',
    dh_tap_index: 1,
    menuList: [],
    // 下拉菜单的选项数组
    array: wx.getStorageSync("qj") == 'hz' || wx.getStorageSync("qj") == 'bz' ? ['图库', '整案'] : ['case', 'Case'],
    // 选中的索引，默认选中第一个（索引为 0）
    selectedIndex: 1,
    caseIndex: undefined,
    showPop: false,
    caseIndexName0: '',
    caseIndexName1: '',
    caseIndexName2: '',
    caseIndexName3: '',
    caseIndexName4: '',
    caseIndexName5: '',
    articleList: [], // 文章列表数据
    page: 1,         // 当前页码（初始为第1页）
    pageSize: 10,    // 每页条数
    isLoading: false, // 是否正在加载
    noMoreData: false, // 是否已加载全部
    k: '',
    xx: '',


    // 收藏相关
    collectType: "case", // 收藏类型：gallery（图库）/ case（整案）
    isCollected: false,     // 是否已收藏
    currentItemId: "", // 当前操作的内容ID（实际应从页面参数获取）
    caseList: [], // 图库收藏列表数据
    caseListID: '', // 图库收藏列表ID



    // 心愿单相关
    showWishPanel: false,   // 是否显示心愿单面板
    wishFolders: [],        // 心愿单文件夹列表
    selectedFolderId: "",   // 选中的文件夹ID
    showCreateDialog: false,// 是否显示新建文件夹弹窗
    newFolderName: "",      // 新文件夹名称
    wishFoldersID: '',

    // 提示框
    showToast: false,
    toastText: "",
    id: '',
    zdylogox: '',
    flxq: '',
  },
  onLoad: function (e) {
    this.setData({
      id: e.id
    })
    this.adPosition2(e.id);
    this.loadWishFolders();   // 加载心愿单文件夹
    this.loadcase();   // 加载心愿单文件夹


   
        
    // WXAPI.jsonDeleteV2({
    //   token: wx.getStorageSync('token'),
    //   id: 300395740
    // })
  },

  

  // 加载图库
  loadcase() {
    // 调用JSON接口获取文件夹列表
    WXAPI.jsonListV3({
      token: wx.getStorageSync('token'),
      type: "case",
      page: 1,
      pageSize: 100
    }).then(res => {
      if (res.code === 0) {
        this.setData({ caseList: res.data.result[0].content.data || [], caseListID: res.data.result[0].id || '' });
      }
    });
  },


  // 加载心愿单文件夹
  loadWishFolders() {
    // 调用JSON接口获取文件夹列表
    WXAPI.jsonListV3({
      token: wx.getStorageSync('token'),
      type: "wish_folder",
      page: 1,
      pageSize: 100
    }).then(res => {
      if (res.code === 0) {
        this.setData({ wishFolders: res.data.result[0].content.data || [], wishFoldersID: res.data.result[0].id });
        console.log(this.data.wishFolders, this.data.wishFoldersID);
      }
    });
  },


  // 显示/隐藏心愿单面板
  showWishPanel() {
    this.setData({ showWishPanel: true });
  },
  hideWishPanel() {
    this.setData({ showWishPanel: false });
  },

  // 选择文件夹
  selectFolder(e) {
    const folderId = e.currentTarget.dataset.id;
    this.setData({ selectedFolderId: folderId }, () => {
      // 选择后自动添加到该文件夹
      this.addToWishFolder(folderId);
    });
  },

  // 添加到选中的文件夹
  addToWishFolder(folderId) {

    let that = this;
    const { currentItemId, collectType } = that.data;
    // 调用JSON接口添加内容到心愿单
    let temp = {
      addTime: Date.now(),
      wzid: that.data.xx.info.id,
      wzimg: that.data.xx.info.pic,
      wztitle: this.data.xx.info.title,
      wztitle_en: this.data.xx.info.descript,
      wzlx: 'za'
    };
    // 获取id
    let tempjson = that.data.wishFolders;
    let isExist = false;
    tempjson.forEach(folder => {
      console.log("aaa", folder);

      if (folder.id == folderId) {
        console.log("bbbb", folder.id, folderId);
        // 判断是否存在
        if (folder.child.some(item => item.wzid == that.data.xx.info.id)) {
          // 存在
          isExist = false;
        } else {
          folder.child.push(temp);
          folder.count = (folder.count || 0) + 1;
          isExist = true;
        }

      }
    });


    setTimeout(() => {
      if (isExist) {
        WXAPI.jsonSetV2({
          token: wx.getStorageSync('token'),
          id: that.data.wishFoldersID, // 唯一ID
          type: "wish_folder",
          content: JSON.stringify({ data: tempjson })
        }).then(res => {
          if (res.code === 0) {
            that.showToast(this.data.qj == 'hz' || this.data.qj == 'bz' ? "添加成功" : "Added to Wish List");
            that.hideWishPanel();
            that.loadWishFolders();
          }
        });

      } else {
        //提示
        that.showToast(that.data.qj == 'hz' || that.data.qj == 'bz' ? "已添加到心愿单" : "Added to wishlist");
      }
    }, 500);


  },



  // 显示/隐藏新建文件夹弹窗
  showCreateFolderDialog() {
    this.setData({ showCreateDialog: true, newFolderName: "" });
  },
  cancelCreateFolder() {
    this.setData({ showCreateDialog: false });
  },

  // 输入文件夹名称
  onFolderNameInput(e) {
    this.setData({ newFolderName: e.detail.value.trim() });
  },

  // 确认创建文件夹
  confirmCreateFolder() {
    if (!this.data.newFolderName) {
      this.showToast(this.data.qj == 'hz' || this.data.qj == 'bz' ? "请输入心愿单名称" : "Please enter wish list name");
      return;
    }

    // 如果文件夹名称已存在，则提示用户
    if (this.data.wishFolders.some(folder => folder.name === this.data.newFolderName)) {
      this.showToast(this.data.qj == 'hz' || this.data.qj == 'bz' ? "心愿单名称已存在" : "Wish list name already exists");
      return;
    }

    const newFolder = {
      id: `folder_${Date.now()}`,
      type: "wish_folder",
      name: this.data.newFolderName,
      count: 0,
      child: [],
      createTime: Date.now()
    };

    let temp = {
      token: wx.getStorageSync('token'),
      type: "wish_folder",
      content: JSON.stringify({ data: [...this.data.wishFolders, newFolder] })
    }
    console.log(this.data.wishFolders.length);

    if (this.data.wishFoldersID) {
      temp.id = this.data.wishFoldersID;
    }

    // 调用JSON接口保存新文件夹
    WXAPI.jsonSetV2(temp).then(res => {
      if (res.code === 0) {
        this.setData({
          wishFolders: [...this.data.wishFolders, newFolder],
          showCreateDialog: false
        });
        this.showToast(this.data.qj == 'hz' || this.data.qj == 'bz' ? "操作成功" : "Operation successful");
      }
    });
  },

  // 显示提示框
  showToast(text) {
    this.setData({ showToast: true, toastText: text });
    setTimeout(() => {
      this.setData({ showToast: false });
    }, 2000);
  },






  // 收藏和取消收藏
  toggleCollect() {
    if (this.data.isCollected) {
      // 取消收藏
      WXAPI.cmsArticleFavDeleteByNewsId(wx.getStorageSync('token'), this.data.xx.info.id).then(res => {
        if (res.code == 0) {
          this.setData({
            isCollected: false
          })
          let temp = this.data.caseList;
          // 删除掉收藏的文章
          temp = temp.filter(item => item.wzid !== this.data.xx.info.id);
          this.setData({
            caseList: temp
          })
          this.showToast(this.data.qj == 'hz' || this.data.qj == 'bz' ? "已取消收藏" : "Canceled Collection");
          let tempjson = {
            token: wx.getStorageSync('token'),
            type: "case",
            id: this.data.caseListID,
            content: JSON.stringify({ data: temp })
          }
          WXAPI.jsonSetV2(tempjson).then(res => {
            if (res.code === 0) {
              // that.showToast(that.data.qj == 'hz' || that.data.qj == 'bz' ? "已添加到心愿单" : "Added to wishlist");
              // that.hideWishPanel();
            }
          });


          // let temp2 = this.data.wishFolders;
          // // 删除掉收藏的文章
          // temp2.forEach(folder => {
          //   folder.child = folder.child.filter(item => item.wzid !== this.data.xx.info.id);
          //   folder.count = folder.child.length;
          // });

          // this.showToast(this.data.qj == 'hz' || this.data.qj == 'bz' ? "已取消收藏" : "Uncollected");
          // let tempjson2 = {
          //   token: wx.getStorageSync('token'),
          //   type: "wish_folder",
          //   id: this.data.wishFoldersID,
          //   content: JSON.stringify({ data: temp })
          // }
          // WXAPI.jsonSetV2(tempjson2).then(res => {
          //   if (res.code === 0) {
          //     this.setData({
          //       wishFolders: temp2
          //     });
          //   }
          // });


        }
      })
    } else {
      // 收藏
      WXAPI.cmsArticleFavPut(wx.getStorageSync('token'), this.data.xx.info.id).then(res => {
        if (res.code == 0) {
          this.setData({
            isCollected: true,
            showWishPanel: true
          })
          let temp = this.data.caseList;
          temp.push({
            addTime: Date.now(),
            wzid: this.data.xx.info.id,
            wztitle: this.data.xx.info.title,
            wztitle_en: this.data.xx.info.descript,
            wzimg: this.data.xx.info.pic,
            wzlx: 'za'
          })
          let tempjson = {
            token: wx.getStorageSync('token'),
            type: "case",
            content: JSON.stringify({ data: temp })
          }
          if (this.data.caseListID) {
            tempjson.id = this.data.caseListID;
          }
          this.showToast(this.data.qj == 'hz' || this.data.qj == 'bz' ? "收藏成功" : "Collected");
          WXAPI.jsonSetV2(tempjson).then(res => {
            if (res.code === 0) {
              // that.showToast(that.data.qj == 'hz' || that.data.qj == 'bz' ? "已添加到心愿单" : "Added to wishlist");
              // that.hideWishPanel();
            }
          });

        }
      })
      this.setData({
        pop: true
      })
    }
  },
  // 上方轮播切换时触发
  handleTopSwiperChange(e) {
    this.setData({
      currentIndex: e.detail.current,
    });
  },
  // 点击图片放大，还可以滑动查看其他图片，还可以下载图片
  handleTopImageTap(e) {
    wx.previewImage({
      current: e.currentTarget.dataset.url,
      urls: this.data.xx.pics.map(item => item.pic),

    });


  },

  // 点击下方缩略图时触发
  handleThumbTap(e) {
    const index = e.currentTarget.dataset.index;
    this.setData({
      currentIndex: index,
    });
  },

  back() {
    wx.navigateBack({
      delta: 1
    })
  },


  // 文章详情
  async adPosition2(a) {
    let res = await WXAPI.cmsArticleDetailV2(a);
    // cmsArticleFavPut cmsArticleFavDeleteByNewsId
    let fav = await WXAPI.cmsArticleFavCheck(wx.getStorageSync('token'), a);
    if (fav.code == -1) {
      this.setData({
        isCollected: false
      })
    } else {
      this.setData({
        isCollected: true
      })
    }
    res.data.info.keywords_sz = res.data.info.keywords.split('、');
    this.setData({
      xx: res.data,
      currentItemId: res.data.info.id
    })

     let resx2 = await WXAPI.cmsCategoryDetail(res.data.info.categoryId);
        if (resx2.code == 0) {
          this.setData({
            flxq: resx2.data.info,
            zdylogox: resx2.data.info.icon,
          })
          // console.log("ddd", that.data.id, resx2.data.info, resx2.data.icon);
        }

  },



  // 加载文章列表（核心方法）
  async loadArticles() {
    // 防止重复请求或无更多数据时继续请求
    if (this.data.isLoading || this.data.noMoreData) return;

    // 显示加载中状态
    this.setData({ isLoading: true });

    try {
      // 调用接口获取数据（传入page和pageSize）
      const res = await WXAPI.cmsArticles({
        categoryId: this.data.selectedIndex == 0 ? '200812' : '200813',
        k: this.data.k,
        page: this.data.page,
        pageSize: this.data.pageSize
      });
      console.log(res);
      // code: 700,msg: "暂无数据"
      if (res.code == 700) {
        this.setData({ noMoreData: true });
        return;
      }


      // 假设接口返回格式：{ code: 0, data: { list: [], total: 100 } }
      if (res.code == 0) {
        const newArticles = res.data.result || [];
        const oldArticles = this.data.articleList;
        const total = res.data.totalRow || 0; // 总条数

        // 拼接新数据
        this.setData({
          articleList: oldArticles.concat(newArticles),
          page: this.data.page + 1, // 页码+1，下次加载下一页
        });

        // 判断是否已加载全部（当前列表长度 >= 总条数）
        if (this.data.articleList.length >= total) {
          this.setData({ noMoreData: true });
        }
      }
    } catch (err) {
      console.error('加载失败：', err);
      wx.showToast({ title: '加载失败', icon: 'none' });
    } finally {
      // 无论成功失败，都关闭加载中状态
      this.setData({ isLoading: false });
    }
  },

  // 滚动到底部触发加载下一页
  onScrollToBottom() {
    this.loadArticles();
  },

  case_nav_footer(e) {
    console.log(e);
    // e.currentTarget.dataset.name 加入到K中，如果有了就不要加了
    if (this.data.k.indexOf(e.currentTarget.dataset.name) == -1) {
      this.setData({
        k: this.data.k + e.currentTarget.dataset.name + ',',
      })

    }

    if (this.data.caseIndex == 0) {
      if (this.data.caseIndexName0 != '') {
        // K中删除之前的名称 ,
        this.setData({

          k: this.data.k.replace(this.data.caseIndexName0, ''),
        })
      }
      this.setData({
        caseIndexName0: this.data.qj == 'hz' || this.data.qj == 'bz' ? e.currentTarget.dataset.name : e.currentTarget.dataset.nameEn,
        showPop: false,
      })
    }
    if (this.data.caseIndex == 1) {
      if (this.data.caseIndexName1 != '') {
        // K中删除之前的名称
        this.setData({
          k: this.data.k.replace(this.data.caseIndexName1, ''),
        })
      }
      this.setData({
        caseIndexName1: this.data.qj == 'hz' || this.data.qj == 'bz' ? e.currentTarget.dataset.name : e.currentTarget.dataset.nameEn,
        showPop: false,
      })
    }
    if (this.data.caseIndex == 2) {
      if (this.data.caseIndexName2 != '') {
        // K中删除之前的名称
        this.setData({
          k: this.data.k.replace(this.data.caseIndexName2, ''),
        })
      }
      this.setData({
        caseIndexName2: this.data.qj == 'hz' || this.data.qj == 'bz' ? e.currentTarget.dataset.name : e.currentTarget.dataset.nameEn,
        showPop: false,
      })
    }
    if (this.data.caseIndex == 3) {
      if (this.data.caseIndexName3 != '') {
        // K中删除之前的名称
        this.setData({
          k: this.data.k.replace(this.data.caseIndexName3, ''),
        })
      }
      this.setData({
        caseIndexName3: this.data.qj == 'hz' || this.data.qj == 'bz' ? e.currentTarget.dataset.name : e.currentTarget.dataset.nameEn,
        showPop: false,
      })
    }
    if (this.data.caseIndex == 4) {
      if (this.data.caseIndexName4 != '') {
        // K中删除之前的名称
        this.setData({
          k: this.data.k.replace(this.data.caseIndexName4, ''),
        })
      }
      this.setData({
        caseIndexName4: this.data.qj == 'hz' || this.data.qj == 'bz' ? e.currentTarget.dataset.name : e.currentTarget.dataset.nameEn,
        showPop: false,
      })
    }
    if (this.data.caseIndex == 5) {
      if (this.data.caseIndexName5 != '') {
        // K中删除之前的名称
        this.setData({
          k: this.data.k.replace(this.data.caseIndexName5, ''),
        })
      }
      this.setData({
        caseIndexName5: this.data.qj == 'hz' || this.data.qj == 'bz' ? e.currentTarget.dataset.name : e.currentTarget.dataset.nameEn,
        showPop: false,
      })
    }

    // k: 现代简约,,大地色,, 会有多个逗号处理一下
    // 替换多个逗号为一个逗号
    this.setData({
      k: this.data.k.replace(/,+/g, ','),
    })

    this.setData({
      // k:'',
      page: 1,
      articleList: [], // 清空已加载数据
      noMoreData: false // 重置加载状态
    });
    this.loadArticles();




  },

  case_nav(e) {
    let temp = e.currentTarget.dataset.index;
    this.setData({
      caseIndex: temp,
      showPop: true,
    })
  },

  async cmsPage() {
    const res = await WXAPI.cmsPage("yt0000")
    if (res.code == 0) {
      let sj = JSON.parse(res.data.info.content);
      console.log("sjsjsj", sj);
      this.setData({
        menuList: sj.menuList || []
      })
    }
  },
  // 下拉选项改变时的回调函数
  bindPickerChange: function (e) {
    console.log('选中的索引为', e.detail.value);
    // 更新选中的索引
    this.setData({
      selectedIndex: e.detail.value
    });
    // 重置页码为第1页
    this.setData({
      // k:'',
      page: 1,
      articleList: [], // 清空已加载数据
      noMoreData: false // 重置加载状态
    });
    this.loadArticles();
    // 可在这里根据选中的选项执行相应的逻辑，比如切换展示不同的内容
    if (e.detail.value == 0) {
      // 选中“图库”时的逻辑
      console.log('选择了图库');
    } else if (e.detail.value == 1) {
      // 选中“整案”时的逻辑
      console.log('选择了整案');
    }
  },


  zdy_top_nav() {
    wx.navigateTo({
      url: '/pages/xl/index',
    })
  },
  dh_tap(e) {
    //console.log(e);
    let temp = e.currentTarget.dataset.id;
    this.setData({
      dh_tap_index: temp
    })
    if (temp == 0) {
      wx.reLaunch({
        url: '/packageYt/index/index',
      })
    }
    if (temp == 1) {
      wx.reLaunch({
        url: '/packageYt/case/index',
      })
    }
    if (temp == 2) {
      wx.reLaunch({
        url: '/packageYt/ting/index',
      })
    }
    if (temp == 3) {
      wx.reLaunch({
        url: '/packageYt/goods/index',
      })
    }
    if (temp == 4) {
      wx.reLaunch({
        url: '/packageYt/my/index',
      })
    }
  },


  onShow: function (e) {
    this.setData({
      qj: wx.getStorageSync("qj") ? wx.getStorageSync("qj") : 'bz'
    })

  },

  async getGoodsList(categoryId, append) {
    if (categoryId == 0) {
      categoryId = "";
    }
    wx.showLoading({
      title: ''
    })
    // https://www.yuque.com/apifm/nu0f75/wg5t98
    const res = await WXAPI.goodsv2({
      categoryId: categoryId,
      page: this.data.curPage,
      pageSize: this.data.pageSize
    })
    wx.hideLoading()
    if (res.code == 404 || res.code == 700) {
      let newData = {
        loadingMoreHidden: false
      }
      if (!append) {
        newData.goods = []
      }
      this.setData(newData);
      return
    }
    let goods = [];
    if (append) {
      goods = this.data.goods
    }
    for (var i = 0; i < res.data.result.length; i++) {
      const item = res.data.result[i]
      const hidden_goods_index = wx.getStorageSync('hidden_goods_index')
      if (hidden_goods_index.indexOf(item.id) != -1) {
        continue
      }
      goods.push(item);
    }
    this.setData({
      loadingMoreHidden: true,
      goods: goods,
    });
  },

  onShareAppMessage: function () {
    return {
      title: '"' + wx.getStorageSync('mallName') + '"-' + (this.data.qj == 'hz' || this.data.qj == 'bz' ? this.data.xx.info.title : this.data.xx.info.descript),
      path: '/packageYt/case/detail_za?id=' + this.data.id + '&inviter_id=' + wx.getStorageSync('uid')
    }
  },
  onShareTimeline() {
    return {
      title: '"' + wx.getStorageSync('mallName') + '" ' + wx.getStorageSync('share_profile'),
      query: 'id=' + this.data.id + '&inviter_id=' + wx.getStorageSync('uid')
      // query: 'inviter_id=' + wx.getStorageSync('uid'),
      // imageUrl: wx.getStorageSync('share_pic')
    }
  },

  // onReachBottom: function () {

  // },
  // onPullDownRefresh: function () {

  // }
})